package com.zch.jh.web.rest;

import com.zch.jh.JhbbApp;
import com.zch.jh.domain.Order;
import com.zch.jh.repository.OrderRepository;
import com.zch.jh.service.OrderService;
import com.zch.jh.service.dto.OrderDTO;
import com.zch.jh.service.mapper.OrderMapper;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;

import static com.zch.jh.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.zch.jh.domain.enumeration.OrderStates;
/**
 * Integration tests for the {@link OrderResource} REST controller.
 */
@SpringBootTest(classes = JhbbApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class OrderResourceIT {

    private static final String DEFAULT_ORDER_CODE = "AAAAAAAAAA";
    private static final String UPDATED_ORDER_CODE = "BBBBBBBBBB";

    private static final ZonedDateTime DEFAULT_ORDER_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_ORDER_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final ZonedDateTime DEFAULT_CANCEL_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_CANCEL_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final ZonedDateTime DEFAULT_DEAL_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_DEAL_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final ZonedDateTime DEFAULT_SEND_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_SEND_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final ZonedDateTime DEFAULT_MARGIN_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_MARGIN_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final ZonedDateTime DEFAULT_PAY_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_PAY_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final ZonedDateTime DEFAULT_CHECKED_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_CHECKED_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final Long DEFAULT_USER_ID = 1L;
    private static final Long UPDATED_USER_ID = 2L;

    private static final Long DEFAULT_ITEM_TYPE_ID = 1L;
    private static final Long UPDATED_ITEM_TYPE_ID = 2L;

    private static final Long DEFAULT_ITEM_ID = 1L;
    private static final Long UPDATED_ITEM_ID = 2L;

    private static final BigDecimal DEFAULT_ORDER_PRICE = new BigDecimal(1);
    private static final BigDecimal UPDATED_ORDER_PRICE = new BigDecimal(2);

    private static final BigDecimal DEFAULT_DEAL_PRICE = new BigDecimal(1);
    private static final BigDecimal UPDATED_DEAL_PRICE = new BigDecimal(2);

    private static final Boolean DEFAULT_IS_LOCK_PRICE = false;
    private static final Boolean UPDATED_IS_LOCK_PRICE = true;

    private static final OrderStates DEFAULT_STATES = OrderStates.WAIT_MARGIN;
    private static final OrderStates UPDATED_STATES = OrderStates.WAIT_SEND;

    private static final BigDecimal DEFAULT_ESTIMATES_QTY = new BigDecimal(1);
    private static final BigDecimal UPDATED_ESTIMATES_QTY = new BigDecimal(2);

    private static final BigDecimal DEFAULT_DEAL_QTY = new BigDecimal(1);
    private static final BigDecimal UPDATED_DEAL_QTY = new BigDecimal(2);

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restOrderMockMvc;

    private Order order;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static Order createEntity(EntityManager em) {
        Order order = new Order()
            .orderCode(DEFAULT_ORDER_CODE)
            .orderTime(DEFAULT_ORDER_TIME)
            .cancelTime(DEFAULT_CANCEL_TIME)
            .dealTime(DEFAULT_DEAL_TIME)
            .sendTime(DEFAULT_SEND_TIME)
            .marginTime(DEFAULT_MARGIN_TIME)
            .payTime(DEFAULT_PAY_TIME)
            .checkedTime(DEFAULT_CHECKED_TIME)
            .userId(DEFAULT_USER_ID)
            .itemTypeId(DEFAULT_ITEM_TYPE_ID)
            .itemId(DEFAULT_ITEM_ID)
            .orderPrice(DEFAULT_ORDER_PRICE)
            .dealPrice(DEFAULT_DEAL_PRICE)
            .isLockPrice(DEFAULT_IS_LOCK_PRICE)
            .states(DEFAULT_STATES)
            .estimatesQty(DEFAULT_ESTIMATES_QTY)
            .dealQty(DEFAULT_DEAL_QTY);
        return order;
    }
    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static Order createUpdatedEntity(EntityManager em) {
        Order order = new Order()
            .orderCode(UPDATED_ORDER_CODE)
            .orderTime(UPDATED_ORDER_TIME)
            .cancelTime(UPDATED_CANCEL_TIME)
            .dealTime(UPDATED_DEAL_TIME)
            .sendTime(UPDATED_SEND_TIME)
            .marginTime(UPDATED_MARGIN_TIME)
            .payTime(UPDATED_PAY_TIME)
            .checkedTime(UPDATED_CHECKED_TIME)
            .userId(UPDATED_USER_ID)
            .itemTypeId(UPDATED_ITEM_TYPE_ID)
            .itemId(UPDATED_ITEM_ID)
            .orderPrice(UPDATED_ORDER_PRICE)
            .dealPrice(UPDATED_DEAL_PRICE)
            .isLockPrice(UPDATED_IS_LOCK_PRICE)
            .states(UPDATED_STATES)
            .estimatesQty(UPDATED_ESTIMATES_QTY)
            .dealQty(UPDATED_DEAL_QTY);
        return order;
    }

    @BeforeEach
    public void initTest() {
        order = createEntity(em);
    }

    @Test
    @Transactional
    public void createOrder() throws Exception {
        int databaseSizeBeforeCreate = orderRepository.findAll().size();
        // Create the Order
        OrderDTO orderDTO = orderMapper.toDto(order);
        restOrderMockMvc.perform(post("/api/orders")
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(orderDTO)))
            .andExpect(status().isCreated());

        // Validate the Order in the database
        List<Order> orderList = orderRepository.findAll();
        assertThat(orderList).hasSize(databaseSizeBeforeCreate + 1);
        Order testOrder = orderList.get(orderList.size() - 1);
        assertThat(testOrder.getOrderCode()).isEqualTo(DEFAULT_ORDER_CODE);
        assertThat(testOrder.getOrderTime()).isEqualTo(DEFAULT_ORDER_TIME);
        assertThat(testOrder.getCancelTime()).isEqualTo(DEFAULT_CANCEL_TIME);
        assertThat(testOrder.getDealTime()).isEqualTo(DEFAULT_DEAL_TIME);
        assertThat(testOrder.getSendTime()).isEqualTo(DEFAULT_SEND_TIME);
        assertThat(testOrder.getMarginTime()).isEqualTo(DEFAULT_MARGIN_TIME);
        assertThat(testOrder.getPayTime()).isEqualTo(DEFAULT_PAY_TIME);
        assertThat(testOrder.getCheckedTime()).isEqualTo(DEFAULT_CHECKED_TIME);
        assertThat(testOrder.getUserId()).isEqualTo(DEFAULT_USER_ID);
        assertThat(testOrder.getItemTypeId()).isEqualTo(DEFAULT_ITEM_TYPE_ID);
        assertThat(testOrder.getItemId()).isEqualTo(DEFAULT_ITEM_ID);
        assertThat(testOrder.getOrderPrice()).isEqualTo(DEFAULT_ORDER_PRICE);
        assertThat(testOrder.getDealPrice()).isEqualTo(DEFAULT_DEAL_PRICE);
        assertThat(testOrder.isIsLockPrice()).isEqualTo(DEFAULT_IS_LOCK_PRICE);
        assertThat(testOrder.getStates()).isEqualTo(DEFAULT_STATES);
        assertThat(testOrder.getEstimatesQty()).isEqualTo(DEFAULT_ESTIMATES_QTY);
        assertThat(testOrder.getDealQty()).isEqualTo(DEFAULT_DEAL_QTY);
    }

    @Test
    @Transactional
    public void createOrderWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = orderRepository.findAll().size();

        // Create the Order with an existing ID
        order.setId(1L);
        OrderDTO orderDTO = orderMapper.toDto(order);

        // An entity with an existing ID cannot be created, so this API call must fail
        restOrderMockMvc.perform(post("/api/orders")
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(orderDTO)))
            .andExpect(status().isBadRequest());

        // Validate the Order in the database
        List<Order> orderList = orderRepository.findAll();
        assertThat(orderList).hasSize(databaseSizeBeforeCreate);
    }


    @Test
    @Transactional
    public void getAllOrders() throws Exception {
        // Initialize the database
        orderRepository.saveAndFlush(order);

        // Get all the orderList
        restOrderMockMvc.perform(get("/api/orders?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(order.getId().intValue())))
            .andExpect(jsonPath("$.[*].orderCode").value(hasItem(DEFAULT_ORDER_CODE)))
            .andExpect(jsonPath("$.[*].orderTime").value(hasItem(sameInstant(DEFAULT_ORDER_TIME))))
            .andExpect(jsonPath("$.[*].cancelTime").value(hasItem(sameInstant(DEFAULT_CANCEL_TIME))))
            .andExpect(jsonPath("$.[*].dealTime").value(hasItem(sameInstant(DEFAULT_DEAL_TIME))))
            .andExpect(jsonPath("$.[*].sendTime").value(hasItem(sameInstant(DEFAULT_SEND_TIME))))
            .andExpect(jsonPath("$.[*].marginTime").value(hasItem(sameInstant(DEFAULT_MARGIN_TIME))))
            .andExpect(jsonPath("$.[*].payTime").value(hasItem(sameInstant(DEFAULT_PAY_TIME))))
            .andExpect(jsonPath("$.[*].checkedTime").value(hasItem(sameInstant(DEFAULT_CHECKED_TIME))))
            .andExpect(jsonPath("$.[*].userId").value(hasItem(DEFAULT_USER_ID.intValue())))
            .andExpect(jsonPath("$.[*].itemTypeId").value(hasItem(DEFAULT_ITEM_TYPE_ID.intValue())))
            .andExpect(jsonPath("$.[*].itemId").value(hasItem(DEFAULT_ITEM_ID.intValue())))
            .andExpect(jsonPath("$.[*].orderPrice").value(hasItem(DEFAULT_ORDER_PRICE.intValue())))
            .andExpect(jsonPath("$.[*].dealPrice").value(hasItem(DEFAULT_DEAL_PRICE.intValue())))
            .andExpect(jsonPath("$.[*].isLockPrice").value(hasItem(DEFAULT_IS_LOCK_PRICE.booleanValue())))
            .andExpect(jsonPath("$.[*].states").value(hasItem(DEFAULT_STATES.toString())))
            .andExpect(jsonPath("$.[*].estimatesQty").value(hasItem(DEFAULT_ESTIMATES_QTY.intValue())))
            .andExpect(jsonPath("$.[*].dealQty").value(hasItem(DEFAULT_DEAL_QTY.intValue())));
    }
    
    @Test
    @Transactional
    public void getOrder() throws Exception {
        // Initialize the database
        orderRepository.saveAndFlush(order);

        // Get the order
        restOrderMockMvc.perform(get("/api/orders/{id}", order.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(order.getId().intValue()))
            .andExpect(jsonPath("$.orderCode").value(DEFAULT_ORDER_CODE))
            .andExpect(jsonPath("$.orderTime").value(sameInstant(DEFAULT_ORDER_TIME)))
            .andExpect(jsonPath("$.cancelTime").value(sameInstant(DEFAULT_CANCEL_TIME)))
            .andExpect(jsonPath("$.dealTime").value(sameInstant(DEFAULT_DEAL_TIME)))
            .andExpect(jsonPath("$.sendTime").value(sameInstant(DEFAULT_SEND_TIME)))
            .andExpect(jsonPath("$.marginTime").value(sameInstant(DEFAULT_MARGIN_TIME)))
            .andExpect(jsonPath("$.payTime").value(sameInstant(DEFAULT_PAY_TIME)))
            .andExpect(jsonPath("$.checkedTime").value(sameInstant(DEFAULT_CHECKED_TIME)))
            .andExpect(jsonPath("$.userId").value(DEFAULT_USER_ID.intValue()))
            .andExpect(jsonPath("$.itemTypeId").value(DEFAULT_ITEM_TYPE_ID.intValue()))
            .andExpect(jsonPath("$.itemId").value(DEFAULT_ITEM_ID.intValue()))
            .andExpect(jsonPath("$.orderPrice").value(DEFAULT_ORDER_PRICE.intValue()))
            .andExpect(jsonPath("$.dealPrice").value(DEFAULT_DEAL_PRICE.intValue()))
            .andExpect(jsonPath("$.isLockPrice").value(DEFAULT_IS_LOCK_PRICE.booleanValue()))
            .andExpect(jsonPath("$.states").value(DEFAULT_STATES.toString()))
            .andExpect(jsonPath("$.estimatesQty").value(DEFAULT_ESTIMATES_QTY.intValue()))
            .andExpect(jsonPath("$.dealQty").value(DEFAULT_DEAL_QTY.intValue()));
    }
    @Test
    @Transactional
    public void getNonExistingOrder() throws Exception {
        // Get the order
        restOrderMockMvc.perform(get("/api/orders/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateOrder() throws Exception {
        // Initialize the database
        orderRepository.saveAndFlush(order);

        int databaseSizeBeforeUpdate = orderRepository.findAll().size();

        // Update the order
        Order updatedOrder = orderRepository.findById(order.getId()).get();
        // Disconnect from session so that the updates on updatedOrder are not directly saved in db
        em.detach(updatedOrder);
        updatedOrder
            .orderCode(UPDATED_ORDER_CODE)
            .orderTime(UPDATED_ORDER_TIME)
            .cancelTime(UPDATED_CANCEL_TIME)
            .dealTime(UPDATED_DEAL_TIME)
            .sendTime(UPDATED_SEND_TIME)
            .marginTime(UPDATED_MARGIN_TIME)
            .payTime(UPDATED_PAY_TIME)
            .checkedTime(UPDATED_CHECKED_TIME)
            .userId(UPDATED_USER_ID)
            .itemTypeId(UPDATED_ITEM_TYPE_ID)
            .itemId(UPDATED_ITEM_ID)
            .orderPrice(UPDATED_ORDER_PRICE)
            .dealPrice(UPDATED_DEAL_PRICE)
            .isLockPrice(UPDATED_IS_LOCK_PRICE)
            .states(UPDATED_STATES)
            .estimatesQty(UPDATED_ESTIMATES_QTY)
            .dealQty(UPDATED_DEAL_QTY);
        OrderDTO orderDTO = orderMapper.toDto(updatedOrder);

        restOrderMockMvc.perform(put("/api/orders")
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(orderDTO)))
            .andExpect(status().isOk());

        // Validate the Order in the database
        List<Order> orderList = orderRepository.findAll();
        assertThat(orderList).hasSize(databaseSizeBeforeUpdate);
        Order testOrder = orderList.get(orderList.size() - 1);
        assertThat(testOrder.getOrderCode()).isEqualTo(UPDATED_ORDER_CODE);
        assertThat(testOrder.getOrderTime()).isEqualTo(UPDATED_ORDER_TIME);
        assertThat(testOrder.getCancelTime()).isEqualTo(UPDATED_CANCEL_TIME);
        assertThat(testOrder.getDealTime()).isEqualTo(UPDATED_DEAL_TIME);
        assertThat(testOrder.getSendTime()).isEqualTo(UPDATED_SEND_TIME);
        assertThat(testOrder.getMarginTime()).isEqualTo(UPDATED_MARGIN_TIME);
        assertThat(testOrder.getPayTime()).isEqualTo(UPDATED_PAY_TIME);
        assertThat(testOrder.getCheckedTime()).isEqualTo(UPDATED_CHECKED_TIME);
        assertThat(testOrder.getUserId()).isEqualTo(UPDATED_USER_ID);
        assertThat(testOrder.getItemTypeId()).isEqualTo(UPDATED_ITEM_TYPE_ID);
        assertThat(testOrder.getItemId()).isEqualTo(UPDATED_ITEM_ID);
        assertThat(testOrder.getOrderPrice()).isEqualTo(UPDATED_ORDER_PRICE);
        assertThat(testOrder.getDealPrice()).isEqualTo(UPDATED_DEAL_PRICE);
        assertThat(testOrder.isIsLockPrice()).isEqualTo(UPDATED_IS_LOCK_PRICE);
        assertThat(testOrder.getStates()).isEqualTo(UPDATED_STATES);
        assertThat(testOrder.getEstimatesQty()).isEqualTo(UPDATED_ESTIMATES_QTY);
        assertThat(testOrder.getDealQty()).isEqualTo(UPDATED_DEAL_QTY);
    }

    @Test
    @Transactional
    public void updateNonExistingOrder() throws Exception {
        int databaseSizeBeforeUpdate = orderRepository.findAll().size();

        // Create the Order
        OrderDTO orderDTO = orderMapper.toDto(order);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restOrderMockMvc.perform(put("/api/orders")
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(orderDTO)))
            .andExpect(status().isBadRequest());

        // Validate the Order in the database
        List<Order> orderList = orderRepository.findAll();
        assertThat(orderList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    public void deleteOrder() throws Exception {
        // Initialize the database
        orderRepository.saveAndFlush(order);

        int databaseSizeBeforeDelete = orderRepository.findAll().size();

        // Delete the order
        restOrderMockMvc.perform(delete("/api/orders/{id}", order.getId())
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<Order> orderList = orderRepository.findAll();
        assertThat(orderList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
